package com.damage.common.web;

import com.damage.common.config.CodeConfig;
import com.damage.common.config.CommonConfig;
import com.damage.common.entity.Employee;
import com.damage.common.entity.Supplier;
import com.damage.common.object.BaseResp;
import com.damage.common.service.ICommonService;
import com.damage.common.util.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/common")
@ResponseBody
@Slf4j
public class CommonController {

    @Autowired
    ICommonService commonService;

    @Autowired
    IdentityService identityService;

    @PostMapping("/login")
    public BaseResp login(String username, String password, String loginType, HttpSession session){
        log.info("username:{}",username);
        log.info("password:{}",password);
        log.info("loginType:{}",loginType);

        if (CommonConfig.LOGIN_TYPE_EMPLOYEE.equals(loginType)){
            //登录的是员工
            Employee employee = commonService.employeeLogin(username, password);
            if (employee == null){
                return BaseResp.error(CodeConfig.ERROR_NO_USER);
            }
            User user = identityService.createUserQuery()
                    .userFirstName(employee.getName())
                    .singleResult();
            session.setAttribute(UserUtil.USER, user);
            log.info("员工" + user.getFirstName() + "登录了!");
            return BaseResp.ok(employee);
        }
        if (CommonConfig.LOGIN_TYPE_SUPPLIER.equals(loginType)){
            Supplier supplier = commonService.supplierLogin(username, password);
            if (supplier == null){
                return BaseResp.error(CodeConfig.ERROR_NO_USER);
            }
            User user = identityService.createUserQuery()
                    .userFirstName(supplier.getName())
                    .singleResult();
            session.setAttribute(UserUtil.USER, user);
            log.info("供应商" + user.getFirstName() + "登录了!");
            return BaseResp.ok(supplier);
        }
        return BaseResp.error("登录出现错误！");
    }

    @PostMapping("/logout")
    public BaseResp logout(HttpSession session){
        session.removeAttribute(UserUtil.USER);
        return BaseResp.ok();
    }
}
